<template>
  <ele-page flex-table>
    <ComHeader :title="`销售单详情[${info?.order_sn}]`" @back="goBack" />
    <ele-bottom-bar :teleported="true">
      <template #extra>
        <el-button v-if="info.is_edit === 1" type="primary" plain @click="onCommand('EDIT')">编辑</el-button>
        <el-button v-if="info.is_sh === 1" type="primary" plain @click="onCommand('SH')">审核</el-button>
        <el-button v-if="info.is_fs === 1" type="danger" plain @click="onCommand('FS')">反审</el-button>
        <el-button v-if="info.is_cd === 1" type="info" @click="onCommand('CD')">取消</el-button>
      </template>
    </ele-bottom-bar>

    <ele-card flex-table bordered :header-style="{ padding: '0 16px' }">
      <template #header>
        <ele-tabs
          v-model="active"
          :items="[
            { name: '1', label: '基础信息' },
            { name: '3', label: '付款信息' },
            { name: '4', label: '操作日志' },
          ]"
          type="plain"
        />
      </template>
      <el-scrollbar>
        <div v-show="active === '1'">
          <el-descriptions title="" :column="4">
            <el-descriptions-item :width="100" label="单据编号">
              <ele-copyable>{{ info.order_sn }}</ele-copyable>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="录单日期">
              {{ info.order_date || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="订单状态">
              {{ info.status_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="发货状态">
              {{ info.out_status_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="货主">
              {{ info.supplier_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="发货仓库">
              {{ info.warehouse_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="客户名称">
              {{ info.customer_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="收货人">
              {{ info.consignee || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="收货电话">
              {{ info.consignee_phone || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="送货地址">
              {{ info.consignee_address || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="物流公司">
              {{ info.logistics_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="物流单号">
              {{ info.logistics_order_sn || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="商品数量">
              {{ info.num || '-' }}
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="税率">
              {{ info.tax_rate > 0 ? `${info.tax_rate}%` : '不开票' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="未税金额">
              {{ info.total || '-' }}
            </el-descriptions-item>
            <template v-if="info.tax_rate > 0">
              <el-descriptions-item :width="100" label="税额">
                {{ info.tax_amount || '-' }}
              </el-descriptions-item>
              <el-descriptions-item :width="100" label="价税合计">
                {{ info.tax_total || '-' }}
              </el-descriptions-item>
            </template>
            <el-descriptions-item :width="100" label="优惠金额">
              {{ info.discount_total || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="实际应付">
              {{ info.sale_total || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="运费">
              {{ info.logistics_total || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建时间">
              {{ info.create_time ? formatDate(info.create_time) : '-' }}
            </el-descriptions-item>
            <el-descriptions-item :span="2" label="备注">
              {{ info.remark || '-' }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions title="" :column="4">
            <el-descriptions-item :span="4" label="附件">
              <div class="flex-inline">
                <FileUpload
                  v-if="info.enclosure?.length"
                  :model-value="JSON.stringify(info.enclosure.map(v => ({ url: v.filepath, name: v.filename })))"
                  readonly
                />
              </div>
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions class="mt-20px" title="" :column="1">
            <template #title>
              <div>商品信息</div>
            </template>
          </el-descriptions>
          <el-table
            :data="info.product"
            border
            style="width: 100%"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="index" label="序" width="60" align="center" />
            <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
            <el-table-column prop="product_code" label="商品编码" align="center" />
            <el-table-column prop="unit" label="主单位" align="center" width="100" />
            <el-table-column prop="multi_unit" label="商品数量" align="center" min-width="120">
              <template #default="{ row }">
                <div class="flex-ca">
                  <div v-for="(item, i) in row.multi_unit" :key="i">
                    <span v-if="i">、</span>{{ item.num || 0 }}{{ item.unit }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="未税单价" align="center" />
            <el-table-column v-if="taxEnable" prop="tax_price" label="含税单价" align="center" />
            <el-table-column prop="total" label="未税金额" align="center" />
            <el-table-column v-if="taxEnable" prop="tax_amount" label="税额" align="center" />
            <el-table-column v-if="taxEnable" prop="tax_total" label="含税金额" align="center" />
          </el-table>
        </div>
        <div v-lazy-show="active === '3'">
          <PagePay :orderId="info.id" />
        </div>
        <div v-lazy-show="active === '4'">
          <PageOperation :orderId="info.id" />
        </div>
      </el-scrollbar>
    </ele-card>
    <PageReview v-model="showReview" remarkDisabled @done="review" />
  </ele-page>
</template>

<script setup>
import PageReview from '@/components/Common/Review.vue'
import FileUpload from '@/components/FileUpload/index.vue'
import PageOperation from './components/operation.vue'
import PagePay from './components/pay.vue'

defineOptions({ name: 'SaleInfo' })

const { formatDate } = utils

const orderId = ref(0)
const route = useRoute()
const router = useRouter()
const { routeTabKey, removePageTab, setPageTabTitle, addPageTab } = utils.usePageTab()

const info = ref({})
const active = ref('1')
const showReview = ref(false)

const taxEnable = computed(() => info.value?.tax_rate > 0)

onMounted(() => {
  orderId.value = route.params?.id

  getInfo()
})

// 激活页面刷新table
utils.useActivatedReload(() => {
  getInfo()
})

function goBack() {
  removePageTab({ key: routeTabKey })
  router.push('/sale/index')
}

function getInfo() {
  utils.get('/sale/info', { id: orderId.value }).then((res) => {
    info.value = res.data
    setPageTabTitle(`销售单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
  })
}

function updateStatus(url, formData, cb) {
  const loadingBox = utils.message('请求中..', 'loading')
  utils.post(url, formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      getInfo()
      showReview.value = false
    }
  }).finally(() => {
    cb && cb()
    loadingBox.close()
  })
}

function review(data, cb) {
  updateStatus('/sale/review', {
    status: data.status,
    id: [info.value.id],
  }, cb)
}

function onCommand(command) {
  if (['EDIT', 'REVISE'].includes(command)) {
    const path = `/sale/index/${command.toLowerCase()}/${info.value.id}`
    addPageTab({
      key: path,
      closable: true,
    })
    router.push(path)
  }
  else if (command === 'SH') {
    showReview.value = true
  }
  else if (command === 'CD') {
    utils.confirm('确定要<span class="px-2px text-danger font-semibold">取消</span>订单吗', '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
      cancelButtonText: '不取消了',
      confirmButtonText: '确定取消',
    }).then(() => {
      updateStatus('/sale/cancel', { id: info.value.id })
    })
  }
  else {
    // YS 审核通过 NS 审核不通过 FS 反审 OK 已结单
    const list = [
      { key: 'YS', title: '审核通过' },
      { key: 'NS', title: '审核不通过' },
      { key: 'FS', title: '反审' },
      { key: 'OK', title: '结单' },
    ]
    const item = list.find(v => v.key === command)
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">${item.title}</span>订单吗`, '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      updateStatus('/sale/review', { id: [info.value.id], status: command })
    })
  }
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['purchase_num', 'total', 'tax_amount', 'tax_total', 'gift_num', 'enter_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => utils.Big(acc).plus(cur[column.property]).valueOf(), 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
